//
//  WeiboStatusCell.swift
//  WEIBO_SWIFT
//
//  Created by 岳挺 on 15/7/2.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

class WeiboStatusCell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource {
    
    //图片地址数组
    var imageArr : [String]?
    
    //配图的宽高约束
    var picViewWidth : NSLayoutConstraint?
    var picViewHeight : NSLayoutConstraint?
    var picViewTop : NSLayoutConstraint?
    
    var itemSize : CGSize?
    
    //转发微博文字
    var forwardLabel : UILabel?
    
    //微博
    var status : Status?{
        didSet{
            icon.sd_setImageWithURL(status?.user?.iconImageURL)
            vipIconView.image = status?.user?.verified_image
            name.text = status!.user!.name
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            vip.image = status?.user?.vipImage
            time.text = "刚刚"
            source.text = status!.source
            content.text = status!.text

            let result = picViewSize(status!)
            picViewTop!.constant = result.viewSize.height == 0 ? 0 : 8
            picViewWidth!.constant = result.viewSize.width
            picViewHeight!.constant = result.viewSize.height
            picLayout.itemSize = result.itemSize
//            picView
            //刷新配图中item
            picView.reloadData()
        }
    }

    //计算cell行高
    func rowHights (status : Status) ->CGFloat{
        self.status = status
        layoutIfNeeded()
        
        return CGRectGetMaxY(footerView.frame) + 10
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        //顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 10))
        
        //添加控件
        addSubview(icon)
        addSubview(vipIconView)
        addSubview(name)
        addSubview(vip)
        addSubview(time)
        addSubview(source)
        addSubview(content)
        addSubview(picView)
        addSubview(footerView)
        
        //添加控件布局
        /**
        1,设置行数，2，设置cell，3，设置行高
        */
        icon.ff_AlignVertical(ff_AlignType.BottomLeft, referView: topView, size: CGSizeMake(40, 40), offset: CGPoint(x: 8, y: 8))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: icon, size: CGSizeMake(20, 20), offset: CGPoint(x: 10, y: 10))
        name.ff_AlignHorizontal(ff_AlignType.TopRight, referView: icon, size: nil, offset: CGPoint(x: 8, y: 0))
        vip.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: name, size: CGSizeMake(20, 20), offset: CGPoint(x: 10, y: 0))
        time.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: icon, size: nil, offset: CGPoint(x: 8, y: 0))
        source.ff_AlignHorizontal(ff_AlignType.TopRight, referView: time, size: nil, offset: CGPoint(x: 8, y: 0))
        
        
        content.ff_AlignVertical(ff_AlignType.BottomLeft, referView: icon, size: nil, offset: CGPoint(x: 0, y: 10))
//        let cons = picView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: content, size: nil, offset: CGPoint(x: 0, y: 8))
        preparPicviewLayout()
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: picView, size: CGSizeMake(UIScreen.mainScreen().bounds.size.width, 49), offset: CGPoint(x: -8, y: 8))

    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    // MARK: - 设置微博配图
    /**缩略图尺寸，90 * 90
    1,计算整个配图区域的尺寸
    1.1当有0张图片的时候返回zero
    1.2当有1按图片原比例缩放
    1.3当有4张图片的时候 2 * 2
    1.4当9图时 3 * 3
    2，根据尺寸设置collection的布局
    3，显示图片
    */
    
    func preparPicviewLayout (){
        picView.delegate = self
        picView.dataSource = self
        
        picLayout.minimumInteritemSpacing = 10
        picLayout.minimumLineSpacing = 10
        
        picView.registerClass(picViewCell.self, forCellWithReuseIdentifier: "item")
    }
    
    func picViewSize (status : Status) -> (itemSize : CGSize , viewSize : CGSize){
        let a = status.picURL?.count ?? 0
        let margin : CGFloat = 10.0
        let itemsize = CGSizeMake(90, 90)
        let picW = itemsize.width
        
        if a == 0 {
            return (itemsize, CGSizeZero)
        }
        
        if a == 1 {
            let key = status.picURL![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
//            if image == nil {
//                return (itemsize, CGSizeZero)
//            }
            
            return (image.size, image.size)
        }
        
        if a  == 4 {
            let w = picW * 2 + margin
            let size = CGSizeMake(w ,w)
            return (itemsize, size)
        }
        
        //每行图片数3
        let rowCount = 3
        //2，3个时候1行5，6时候2行，7，8，9时3行
        //行数
        let row = (a - 1) / rowCount + 1
        let w = picW * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = picW * CGFloat(row) + CGFloat(row - 1) * margin
        return (itemsize, CGSizeMake(w, h))
    }
    
    func recordPicViewLayoutConstrains (cons : [NSLayoutConstraint]) {
        picViewTop = picView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        picViewWidth = picView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        picViewHeight = picView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    //MARK: - collection的数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let picNum = status?.picURL?.count ?? 0
        return picNum
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let itemURL = status!.picURL![indexPath.item]
        let item = collectionView.dequeueReusableCellWithReuseIdentifier("item", forIndexPath: indexPath) as! picViewCell
        item.imageURL = itemURL
        return item
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
    }
    
    // MARK: - 控件懒加载
    //头像
    lazy var icon = UIImageView()
    //名字
    lazy var name =  UILabel()
    //vip
    lazy var vip = UIImageView()
    //认证标志
    lazy var vipIconView = UIImageView()
    //时间
    lazy var time = UILabel()
    //来源
    lazy var source = UILabel()
    //内容
    lazy var content : UILabel = {
        let l = UILabel()
        l.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
        l.numberOfLines = 0
        
        return l
        }()
    //微博配图
    lazy var picLayout = UICollectionViewFlowLayout()
    lazy var picView : UICollectionView = {
        let v = UICollectionView(frame: CGRectZero, collectionViewLayout:self.picLayout)
        v.backgroundColor = UIColor.whiteColor()
        return v
        }()
    
    //微博footerView
    lazy var footerView : weiboFooterView = weiboFooterView()
    
}

//MARK: - 配图cell
private class picViewCell : UICollectionViewCell {
    var imageURL : NSURL? {
        didSet{
            let key = imageURL?.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            picImageView.image = image
        }
    }
    
    lazy var picImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(picImageView)
        
        picImageView.ff_Fill(self)
        picImageView.contentMode = UIViewContentMode.ScaleAspectFill
        picImageView.clipsToBounds = true
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

//MARK: - 自定义footerView
class weiboFooterView : UIView {

    lazy var retweetBtn : UIButton = UIButton(title: "转发", image: "timeline_icon_retweet", font: 13.0)
    lazy var commentBtn : UIButton = UIButton(title: "评论", image: "timeline_icon_comment", font: 13.0)
    lazy var likeBtn : UIButton = UIButton(title: "点赞", image: "timeline_icon_unlike", font: 13.0)
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        retweetBtn.backgroundColor = UIColor.whiteColor()
        commentBtn.backgroundColor = UIColor.whiteColor()
        likeBtn.backgroundColor = UIColor.whiteColor()
        addSubview(retweetBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        self.ff_HorizontalTile([retweetBtn,commentBtn,likeBtn], insets: UIEdgeInsetsMake(1, 0, 0, 0))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
